/*

*/
#pragma once

#include<sys/epoll.h>
#include<unistd.h>
#include<functional>
#include<unordered_map>
#include<string>
#include<memory>
#include<map>
#include"eventloop.h"
#include"timer.h"
#include"tcp_connection.h"

class TcpConnection;

enum HttpMethod { POST = 1, GET, HEAD };
enum HttpVersion { HTTP_10 = 1, HTTP_11 };

enum ProcessState {
  STATE_PARSE_URI = 1,
  STATE_PARSE_HEADERS,
  STATE_RECV_BODY,
  STATE_ANALYSIS,
  STATE_FINISH
};

enum URIState {
  PARSE_URI_AGAIN = 1,
  PARSE_URI_ERROR,
  PARSE_URI_SUCCESS,
};

enum HeaderState {
  PARSE_HEADER_SUCCESS = 1,
  PARSE_HEADER_AGAIN,
  PARSE_HEADER_ERROR
};

enum AnalysisState { ANALYSIS_SUCCESS = 1, ANALYSIS_ERROR };

enum ParseState {
  H_START = 0,
  H_KEY,
  H_COLON,
  H_SPACES_AFTER_COLON,
  H_VALUE,
  H_CR,
  H_LF,
  H_END_CR,
  H_END_LF
};

class TimerNode;

class HttpData: public std::enable_shared_from_this<HttpData>
{
private:
    std::shared_ptr<TcpConnection>  m_tcp_server;
    HttpMethod m_method;   //method
    HttpVersion m_httpversion; //version

    string m_filename;//uri
    string m_path;
    int m_readpos;//msg pos
    //消息处理相关标记
    ProcessState m_state;
    ParseState m_hState;

    bool m_keepalive;
    std::map<string,string> m_headers;
    std::weak_ptr<TimerNode> m_timer;
public:
    //下面几个为普通成员构造函数
    HttpData(EventLoop* p, int fd,std::string path="/root/web-server/www");
    ~HttpData() = default;  //要关闭fd才可以
    void reset();
    void seperateTimer();
    EventLoop *getLoop();
    void handleClose();
    void newEvent();
    shared_ptr<Channel> getChannel();
public:
    //提供一个钩子，当添加当前连接的FD到epoll队列上时，由linkTimer()其初始化timer_
    void linkTimer(shared_ptr<TimerNode> m) { m_timer = m; }
    URIState parse_URI();
    HeaderState parse_Headers();
    AnalysisState analysisRequest();
    int process();
};